package dev.entao.travel.model

import dev.entao.base.*
import dev.entao.core.OnHttpContext
import dev.entao.core.controllers.scaleImageUrl
import dev.entao.json.YsonObject
import dev.entao.page.OptionList
import dev.entao.page.RefUpload
import dev.entao.page.UploadImage
import dev.entao.page.displayString
import dev.entao.sql.*
import java.sql.Time

@Label("用户")
class User : Model() {

    @Label("ID")
    @PrimaryKey
    @AutoInc(15236)
    var id: Int by model

    @Label("UUID")
    var uuidCode: String? by model

    @NullValue("")
    @Index
    @Label("微信OpenID")
    var openid: String by model

    @Unique
    @Label("手机号")
    //@FixLength(11)
    @MaxLength(16)
    @Index
    var phone: String by model

    @HideClient
    @Label("密码")
    var pwd: String by model

    @Label("名称")
    @Index
    var nickName: String by model

    @Label("身份证")
    @MaxLength(32) // 18
    var identNum: String? by model

    @Label("状态")
    @OptionList("0:激活", "1:冻结", "2:删除")
    var status: Int by model

    @UploadImage(32, 360, 600)
    @Label("头像")
    @RefUpload(5)
//	@RefModel(Upload::class, "id")
    var portrait: Int? by model

    @Index
    @Label("注册日期")
    var regDate: DateSQL? by model

    @Index
    @Label("注册时间")
    var regTime: Time? by model

    @Label("登录日期")
    var loginDate: DateSQL? by model

    @Label("登录时间")
    var loginTime: Time? by model

    @HideClient
    @Label("密保问题")
    var ask: String? by model

    @HideClient
    @Label("密保答案")
    var answer: String? by model

    @NullValue("0")
    @Index
    @Label("金币")
    @Decimal(11, 2)
    var coin: Double by model

    @NullValue("0")
    @Label("积分")
    var score: Int by model

    @OptionList("0:否", "1:是")
    @NullValue("0")
    @Label("内部员工")
    @Index
    var internalMem: Int by model

    @NullValue("0")
    @OptionList("0:手机号密码", "1:一键登录", "2:微信登录")
    var regType: Int by model

    //用于微信登录
    @NullValue("0")
    @Label("手机已验证")
    var phoneVerified: Int by model

    companion object : ModelClass<User>() {
        const val YES = 1
        const val NO = 0

        const val REG_PHONE_PWD = 0
        const val REG_MOBILE = 1
        const val REG_WX = 2

    }
}

context (OnHttpContext)
fun User.jsonData(): YsonObject {
    val user = this
    return this.jsonClient().apply {
        "statusName" TO user::status.displayString(null)
        "portraitUrl" TO scaleImageUrl(user.portrait ?: 0, 600)
        if (user.regType == User.REG_WX && user.phoneVerified == 0) {
            "phone" TO ""
        }
    }
}